<template>
  <el-card shadow="never" style="width: 100%">
    <div>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card :class="{'selected': chartData.type === 0}"
                   class="data-card"
                   shadow="hover"
                   @click="switchDataType(0)" style="height: 12vh">
            <div class="card-content">
              <el-row align="middle">
                <el-col :span="4">
                  <el-icon class="icon-timer"><Timer/></el-icon>
                </el-col>
                <el-col :span="20">
                  <div class="content-text">
                    代码执行时间排行榜
                    <strong>{{ runTime }}</strong><br>
                    击败了{{ percentBeatRunTime }}%的人
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-card>

        </el-col>
        <el-col :span="12">
            <el-card :class="{'selected': chartData.type === 1}"
                     class="data-card"
                     shadow="hover"
                     @click="switchDataType(1)">
              <div class="card-content">
                <el-row align="middle">
                  <el-col :span="4">
                    <el-icon class="icon-cpu"><Cpu/></el-icon>
                  </el-col>
                  <el-col :span="20">
                    <div class="content-text">
                      内存消耗大小排行榜
                      <strong>{{ memory }}</strong><br>
                      击败了{{ percentBeatMemory }}%的人
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-card>
        </el-col>
      </el-row>
    </div>
    <div style="width: 100%; display: flex; justify-content: center;">
      <div ref="chartContainer" :style="{width: '100%', height: '25vh'}"></div>
    </div>
  </el-card>
</template>

<style scoped>
.selected {
  background-color: #f0f0f0; /* 淡灰色背景表示选中状态 */
}
.selected {
  border-color: #409eff; /* Element UI 主题蓝色 */
}

.data-card {
  height: 12vh;
  cursor: pointer;
}

.icon-timer {
  font-size: 20px; /* 调整图标大小 */
  color: #409eff; /* 图标颜色 */
}

.card-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.content-text h3 {
  margin: 0; /* 移除h3默认的margin */
  font-weight: normal; /* 标准字重 */
}

.content-text strong {
  font-size: 16px; /* 强调文字大小 */
  color: #333; /* 字体颜色 */
}
.selected {
  border-color: #409eff; /* Element UI 主题蓝色 */
}

.data-card {
  height: 12vh;
  cursor: pointer;
}

.icon-cpu {
  font-size: 20px; /* 调整图标大小 */
  color: #409eff; /* 图标颜色 */
}

.card-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.content-text h3 {
  margin: 0; /* 移除h3默认的margin */
  font-weight: normal; /* 标准字重 */
}

.content-text strong {
  font-size: 16px; /* 强调文字大小 */
  color: #333; /* 字体颜色 */
}
</style>

<script setup>
import axios from "axios";
import {onMounted, ref, reactive, computed, nextTick} from "vue";
import * as echarts from 'echarts';
import {Cpu, Timer} from "@element-plus/icons-vue";

const props = defineProps({
  ProblemId: String,
  runTime: String,
  memory: String
});

const chartContainer = ref(null);
const chartInstance = ref(null);

const chartData = reactive({
  runTimeValues: [],
  memoryValues: [],
  type: 0
});

const stripUnit = (value) => parseFloat(value.replace(/[^0-9.]/g, ''));

const findNearestIndex = (arr, target) => {
  return arr
      .map((x, i) => [Math.abs(x - target), i])
      .sort(([a], [b]) => a - b)[0][1];
};

const percentBeatRunTime = computed(() => {
  if (chartData.runTimeValues.length > 0) {
    const strippedRunTime = stripUnit(props.runTime);
    const runTimeValueIndex = findNearestIndex(chartData.runTimeValues, strippedRunTime);
    if (runTimeValueIndex !== undefined) {
      const totalBelow = chartData.runTimeValues.slice(0, runTimeValueIndex).reduce((acc, val) => acc + val, 0);
      return ((totalBelow / chartData.runTimeValues.reduce((acc, val) => acc + val, 0)) * 100).toFixed(2);
    }
  }
  return 'N/A';
});

const percentBeatMemory = computed(() => {
  if (chartData.memoryValues.length > 0) {
    const strippedMemory = stripUnit(props.memory);
    const memoryValueIndex = findNearestIndex(chartData.memoryValues, strippedMemory);
    if (memoryValueIndex !== undefined) {
      const totalBelow = chartData.memoryValues.slice(0, memoryValueIndex).reduce((acc, val) => acc + val, 0);
      return ((totalBelow / chartData.memoryValues.reduce((acc, val) => acc + val, 0)) * 100).toFixed(2);
    }
  }
  return 'N/A';
});

const switchDataType = async (type) => {
  chartData.type = type;
  console.log(props.ProblemId)
  await loadProblemDetailsAndRenderChart(props.ProblemId, type);
};

const loadProblemDetailsAndRenderChart = async (problemId, type) => {
  const api = `/oj/rank/oj/statistics`;
  try {
    const response = await axios.get(api, {
      params: {problemId},
    });

    const filteredData = response.data.data.filter(item => item.type === type);
    if (filteredData.length > 0) {
      const keyValuePairs = filteredData.map(item => ({
        key: item.key,
        value: item.value
      }));
      keyValuePairs.sort((a, b) => parseFloat(a.key) - parseFloat(b.key));
      const sortedKeys = keyValuePairs.map(pair => `${pair.key}` + (type === 0 ? 'ms' : 'kb'));
      const sortedValues = keyValuePairs.map(pair => pair.value);

      if (type === 0) {
        chartData.runTimeValues = sortedValues;
      } else {
        chartData.memoryValues = sortedValues;
      }

      await initializeChart(sortedKeys, sortedValues, type);
    } else {
      console.warn('No data found for selected type.');
    }
  } catch (error) {
    console.error('Error loading and rendering chart details:', error);
  }
};

const initializeChart = async (keys, values, type) => {
  const targetValue = type === 0 ? stripUnit(props.runTime) : stripUnit(props.memory);
  const items = keys.map((key, index) => ({
    key: parseFloat(key),
    value: values[index],
    color: parseFloat(key) === targetValue ? 'rgba(12,1,1,0.8)' : 'rgba(179,179,179,0.5)'
  }));
  items.sort((a, b) => a.key - b.key);

  const sortedKeys = items.map(item => `${item.key}` + (type === 0 ? 'ms' : 'kb'));
  const percentageValues = items.map(item => Math.round(item.value * 100)); // 直接在映射时取整
  const colors = items.map(item => item.color); // 收集颜色配置

  await nextTick();
  if (!chartInstance.value) {
    chartInstance.value = echarts.init(chartContainer.value);
  }

  const option = {
    backgroundColor: "#fff",
    grid: {
      bottom: 90
    },
    tooltip: {
      trigger: 'item', // 注意触发类型，应为 'item' 而非 'axis'
      axisPointer: {
        type: 'shadow' // 指示器类型
      },
      formatter: function (params) {
        // 格式化函数调整，保留整数百分比
        return `${Math.round(params.value)}% 的用户使用了类似的解法<br>RunTimes: ${params.name}`;
      }
    },
    xAxis: {
      type: 'category',
      data: sortedKeys,
      silent: false,
      splitLine: {
        show: false
      },
      splitArea: {
        show: false
      }
    },
    yAxis: {
      type: 'value',
      splitArea: {
        show: false
      },
      axisLabel: {
        formatter: '{value}%' // Y轴标签也仅显示整数百分比
      }
    },
    series: [
      {
        type: 'bar',
        data: percentageValues.map((value, index) => ({value, itemStyle: {color: colors[index]}})),
        barWidth: '50%', // 控制条形的宽度
        barGap: '20%' // 增加条形之间的间隔
      }
    ]
  };

  chartInstance.value.setOption(option, true); // true to not merge with previous options
};

onMounted(() => {
  switchDataType(0); // Initialize with type 0
});
</script>
